//
//  LoginViewController.m
//  wifi4.2
//
//  Created by 郭四虎 on 15/11/13.
//  Copyright © 2015年 YouKu. All rights reserved.
//

#import "LoginViewController.h"
#import "RegistViewController.h"
#import "MyTabBarController.h"
#import "MyMD5.h"
#import "ForgetPasswordControllerViewController.h"

#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>

typedef enum{
    typeQQ = 2,
    typeWEXIN,
    typeWEIBO
} type;

@interface LoginViewController ()
{
    UIImageView *_backIma;
    NSString *_ipAddress;
}

@property (weak, nonatomic) IBOutlet UITextField *accountTf;
@property (weak, nonatomic) IBOutlet UITextField *passwordTf;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //[self creatSharelogin];
    //_accountTf.text = @"15255135603";
   // _accountTf.text = @"18256087122";
    
    //_ipAddress = [Myuser getIPAddress];
    NSLog(@"%@",_ipAddress);
    //_accountTf.text = @"18888888888";
    _accountTf.keyboardType = UIKeyboardTypeDecimalPad;
    //_passwordTf.text = @"123456";
    
    [_accountTf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_passwordTf setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;

}
- (IBAction)popView:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)loginClick:(UIButton *)sender {
    
    NSLog(@"%@",NSHomeDirectory());
    
    if (!_accountTf.text.length || !_passwordTf.text.length) {
        
        [self.view Message:@"账号或密码不能为空" HiddenAfterDelay:1];
        return;
    }
    
        NSString *mdPwd = [MyMD5 md5:_passwordTf.text];
//        NSDictionary *parameters = @{@"login_id":_accountTf.text,@"password":mdPwd,@"login_ip":_ipAddress,@"login_date":[MyDateformater getCurrentDate]};
        NSDictionary *parameters = @{@"login_id":_accountTf.text,@"password":mdPwd,@"login_date":[MyDateformater getCurrentDate]};
        [MyAFN POST:LOGIN parameters:parameters block:^(id responseObject) {

            NSDictionary *dic = responseObject;
        
            if (dic) {
                if ([[dic objectForKey:@"status"]integerValue]) {
                    
                    [MobClick profileSignInWithPUID:_accountTf.text];
                    
                    [[Myuser sharedUser]setValuesForKeysWithDictionary:dic];
                    
                    [[NSUserDefaults standardUserDefaults]setObject:_accountTf.text forKey:@"userid"];
                    
                    
                    [[NSUserDefaults standardUserDefaults]setObject:mdPwd forKey:@"userpwd"];
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserinfo" object:nil];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }else{
                    [self performSelector:@selector(message:) withObject:[dic objectForKey:@"msg"] afterDelay:0.5];
                }
            }else{
                [self.view performSelector:@selector(Message:) withObject:@"未知错误" afterDelay:0.5];
            }
        }error:^(NSError *error) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserinfo" object:nil];
        }fromController:self];
}

- (void)message:(NSString *)msg
{
[self.view Message:msg HiddenAfterDelay:1];
}


- (IBAction)goRegist:(UIButton *)sender {
    
    RegistViewController *regiest = [[RegistViewController alloc]init];
    
    [self.navigationController pushViewController:regiest animated:YES];
}
- (IBAction)forgetPassword:(id)sender {
    
    ForgetPasswordControllerViewController *forget = [[ForgetPasswordControllerViewController alloc]init];
    if (_accountTf.text) {
        forget.number = _accountTf.text;
    }
    [self.navigationController pushViewController:forget animated:YES];
}

- (IBAction)loginQQ:(UIButton *)sender {//QQ登录
    NSLog(@"QQ");
    
    [ShareSDK getUserInfo:SSDKPlatformTypeQQ
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         if (state == SSDKResponseStateSuccess)
         {
             
             NSLog(@"uid=%@",user.uid);
             NSLog(@"%@",user.credential);
             NSLog(@"token=%@",user.credential.token);
             NSLog(@"nickname=%@",user.nickname);
             NSLog(@"icon=%@",user.icon);
             
             [MobClick profileSignInWithPUID:user.uid provider:@"QQ"];
             
             [self thirdLoginWithid:user.uid andName:user.nickname andIcon:user.icon andType:typeQQ];
         }
         
         else
         {
             NSLog(@"%@",error);
         }
     }];
}
- (IBAction)loginWeixin:(UIButton *)sender {//微信登录
    NSLog(@"weixin");

    [ShareSDK getUserInfo:SSDKPlatformTypeWechat
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         if (state == SSDKResponseStateSuccess)
         {
             
             NSLog(@"uid=%@",user.uid);
             NSLog(@"%@",user.credential);
             NSLog(@"token=%@",user.credential.token);
             NSLog(@"nickname=%@",user.nickname);
             NSLog(@"icon=%@",user.icon);
             
             [MobClick profileSignInWithPUID:user.uid provider:@"WX"];
             
             [self thirdLoginWithid:user.uid andName:user.nickname andIcon:user.icon andType:typeWEXIN];
         }
         
         else
         {
             NSLog(@"%@",error);
         }
         
     }];
}
- (IBAction)loginWeibo:(UIButton *)sender {//微博登录
    NSLog(@"weibo");
    
    
    [ShareSDK getUserInfo:SSDKPlatformTypeSinaWeibo 
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         if (state == SSDKResponseStateSuccess)
         {
             
             NSLog(@"uid=%@",user.uid);
             NSLog(@"%@",user.credential);
             
//             NSDictionary *dic = (NSDictionary *)user.credential;
//             NSLog(@"%@",dic[@"app"]);
             NSLog(@"token=%@",user.credential.token);
             NSLog(@"nickname=%@",user.nickname);
             NSLog(@"icon=%@",user.icon);
             
             [MobClick profileSignInWithPUID:user.uid provider:@"WB"];
             
             [self thirdLoginWithid:user.uid andName:user.nickname andIcon:user.icon andType:typeWEIBO];
         }
         
         else
         {
             NSLog(@"%@",error);
         }
         
     }];
    
}

- (void)thirdLoginWithid:(NSString *)uid andName:(NSString *)name
                 andIcon:(NSString *)icon andType:(type)type
{
    NSLog(@"%@",uid);
    [MyAFN POST:REGISTCHECK parameters:@{@"uuid":uid} block:^(id responseObject) {
        NSDictionary *response = responseObject;
        if ([[response objectForKey:@"status"]integerValue]) {
            
            [self thirdRegisterWithid:uid andName:name andIcon:icon andType:type];
        }else{
            [self getUserInfobyuuid:uid andName:name andIcon:icon andType:type];
        }
        
        
    } error:^(NSError *error) {
        
    } fromController:self];
}

- (void)thirdRegisterWithid:(NSString *)uid andName:(NSString *)name
                    andIcon:(NSString *)icon andType:(type)type
{
    
    NSDictionary *parameter = @{@"login_id":uid,@"uuid":uid,@"password":[MyMD5 md5:@"123456"],@"login_type":@(type),@"name":name,@"create_date":[MyDateformater getCurrentDate],@"photo":icon};
    
    NSLog(@"%@",parameter);
    
    [MyAFN POST:REGIST parameters:parameter block:^(id responseObject) {
        
        NSDictionary *registDic = responseObject;
        
        if ([[registDic objectForKey:@"status"]integerValue]) {
            
            [MyAFN POST:USERINFO parameters:@{@"login_id":uid} block:^(id responseObject) {
                NSDictionary *response = responseObject;
                
                if ([response objectForKey:@"status"]) {
                    
                    [[NSUserDefaults standardUserDefaults]setObject:uid forKey:@"userid"];
                    //[[NSUserDefaults standardUserDefaults]setObject:[MyMD5 md5:@"123456"] forKey:@"userpwd"];
                    
                    [Myuser sharedUser].login_id = uid;
                    
                    NSString *str;
                    if ([response objectForKey:@"name"]) {
                        str = [response objectForKey:@"name"];
                        
                    }else{
                        str = name;
                    }
                    [Myuser sharedUser].name = str;
                    
                    NSString *url;
                    if ([response objectForKey:@"photo"]) {
                       // url = [NSString stringWithFormat:@"%@?url=%@",GETICON,[response objectForKey:@"photo"]];
                        url = [response objectForKey:@"photo"];
                        
                    }else{
                        url = icon;
                        
                    }
                    [[NSUserDefaults standardUserDefaults]setObject:url forKey:@"usericon"];
                    [Myuser sharedUser].icon = url;
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserinfo" object:nil];
                    
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    
                }
                
            } error:^(NSError *error) {
                
            } fromController:self];
            
            
            
        }else{
            [self performSelector:@selector(showmsg) withObject:nil afterDelay:0.5];
        }
    }error:^(NSError *error) {
        
    } fromController:self];
}

- (void)getUserInfobyuuid:(NSString *)uuid andName:(NSString *)name
                  andIcon:(NSString *)icon andType:(type)type
{
    [MyAFN POST:USERINFO parameters:@{@"login_id":uuid} block:^(id responseObject) {
        NSDictionary *response = responseObject;
        
        if ([response objectForKey:@"status"]) {
            
            [[Myuser sharedUser]setValuesForKeysWithDictionary:response];
            
            NSString *loginid;
            if ([response objectForKey:@"login_id"]) {
                
                loginid = [response objectForKey:@"login_id"];
            }else{
        
                loginid = uuid;
            }
            [[NSUserDefaults standardUserDefaults]setObject:loginid forKey:@"userid"];
            [Myuser sharedUser].login_id = loginid;
            
//            [[NSUserDefaults standardUserDefaults]setObject:[MyMD5 md5:@"123456"] forKey:@"userpwd"];
            
            NSString *myname;
            if ([response objectForKey:@"name"]) {
                myname = [response objectForKey:@"name"];
    
            }else{
                myname = name;
                
            }
            
            [Myuser sharedUser].name = myname;
            
            NSString *url;
            if ([response objectForKey:@"photo"]) {
                
                //url = [NSString stringWithFormat:@"%@?url=%@",GETICON,[response objectForKey:@"photo"]];
                url = [response objectForKey:@"photo"];
                
            }else{
                url = icon;
            }
            [[NSUserDefaults standardUserDefaults]setObject:url forKey:@"usericon"];
            [Myuser sharedUser].icon = url;
            
            [self.navigationController popToRootViewControllerAnimated:YES];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserinfo" object:nil];
            
        }
        
    } error:^(NSError *error) {
        
    } fromController:self];
}

- (void)showmsg
{
    [self.view Message:@"登录失败,请重试" HiddenAfterDelay:1];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
